import random
from typing import Optional, List
from sqlalchemy.orm import Session

from db import models

INITIAL_FORMULAS = [
    r"E = mc^2",
    r"a^2 + b^2 = c^2",
    r"\sin^2\theta + \cos^2\theta = 1",
    r"F = G \frac{m_1 m_2}{r^2}",
    r"\oint_C \mathbf{B} \cdot d\mathbf{l} = \mu_0 I_{\text{enc}}"
]

def create_initial_formulas(db: Session):
    # Check if formulas already exist to avoid duplicates on reload
    if db.query(models.Formula).count() == 0:
        for latex_str in INITIAL_FORMULAS:
            db_formula = models.Formula(latex=latex_str)
            db.add(db_formula)
        db.commit()

def get_random_formula(db: Session) -> Optional[models.Formula]:
    """Fetches a random formula from the database."""
    # A more efficient way for large tables would be to get count and random offset
    # but for a small number of formulas, this is perfectly fine.
    formulas = db.query(models.Formula).all()
    if not formulas:
        return None
    return random.choice(formulas)


def get_all_formulas(db: Session) -> List[models.Formula]:
    """Get all formulas from the database."""
    return db.query(models.Formula).all()


def get_formula_by_id(db: Session, formula_id: int) -> Optional[models.Formula]:
    """Get a formula by its ID."""
    return db.query(models.Formula).filter(models.Formula.id == formula_id).first()


def create_formula(db: Session, latex: str) -> models.Formula:
    """Create a new formula."""
    db_formula = models.Formula(latex=latex)
    db.add(db_formula)
    db.commit()
    db.refresh(db_formula)
    return db_formula


def update_formula(db: Session, formula_id: int, latex: str) -> Optional[models.Formula]:
    """Update an existing formula."""
    db_formula = get_formula_by_id(db, formula_id)
    if db_formula:
        db_formula.latex = latex
        db.commit()
        db.refresh(db_formula)
    return db_formula


def delete_formula(db: Session, formula_id: int) -> bool:
    """Delete a formula by its ID. Returns True if deleted, False if not found."""
    db_formula = get_formula_by_id(db, formula_id)
    if db_formula:
        db.delete(db_formula)
        db.commit()
        return True
    return False
